import createVanilla from 'zustand/vanilla'
import { subscribeWithSelector } from 'zustand/middleware'
import create from 'zustand'
import { OftenModel } from '@/api/manager/often/interface'
import { IStatusIcon } from '@/pages/manager/components'
import shallow from 'zustand/shallow'

type StateStore = {
	list: OftenModel[]
	itemTotalStatus: IStatusIcon['totalStatus']
}
type IStore = StateStore & {
	update: (d: Partial<StateStore>) => void
	reset: () => void
	delMts: (mtKeys: string[]) => void
}
const initialState: StateStore = {
	list: [],
	itemTotalStatus: {
		vmp: false,
		mix: false,
		poll: false,
		dcs: false,
	},
}
export const store = createVanilla<IStore>()(
	subscribeWithSelector((set, get) => ({
		...initialState,
		update: (d) => set({ ...d }),
		reset: () => set(initialState),
		delMts: (mtKeys) => {
			const list = get().list
			let result = list.filter((x) => !mtKeys.includes(x.mtKey))
			set({ list: result })
		},
	}))
)
export const useTableOftenStore = create(store)
useTableOftenStore.subscribe(
	(state) => {
		const list = state.list
		let vmp = false,
			mix = false,
			poll = false,
			dcs = false
		for (const item of list) {
			if (item.mcc.isMt && item.mcc.status.isVmp) {
				vmp = true
			}
			if (item.mcc.isMt && item.mcc.status.isMix) {
				mix = true
			}
			if (item.mcc.isMt && item.mcc.status.isPoll) {
				poll = true
			}
			if (item.mcc.isMt && item.mcc.status.isDcs) {
				dcs = true
			}
		}
		return { vmp, mix, poll, dcs }
	},
	(cur) => {
		useTableOftenStore.setState({
			itemTotalStatus: cur,
		})
	},
	{
		equalityFn: shallow,
	}
)
